<template>
  <div class="approval-diagnosis-container">
    <h2>审核状态问题诊断</h2>
    
    <!-- 诊断步骤 -->
    <el-card class="diagnosis-card">
      <div class="card-header">
        <h3>诊断步骤</h3>
        <el-button type="primary" @click="runDiagnosis" :loading="diagnosing">
          开始诊断
        </el-button>
      </div>
      
      <el-steps :active="currentStep" finish-status="success" align-center>
        <el-step title="检查数据" description="检查当前数据状态" />
        <el-step title="测试审核" description="执行审核操作" />
        <el-step title="验证更新" description="验证状态是否正确更新" />
        <el-step title="生成报告" description="生成诊断报告" />
      </el-steps>
    </el-card>
    
    <!-- 诊断结果 -->
    <el-card class="result-card" v-if="diagnosisResults.length > 0">
      <div class="card-header">
        <h3>诊断结果</h3>
        <el-button type="warning" @click="clearResults">清空结果</el-button>
      </div>
      
      <div class="diagnosis-results">
        <div 
          v-for="(result, index) in diagnosisResults" 
          :key="index" 
          class="result-item"
          :class="result.type"
        >
          <div class="result-header">
            <span class="result-time">{{ result.time }}</span>
            <span class="result-type" :class="result.type">{{ result.type.toUpperCase() }}</span>
          </div>
          <div class="result-message">{{ result.message }}</div>
          <div v-if="result.data" class="result-data">
            <pre>{{ JSON.stringify(result.data, null, 2) }}</pre>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 测试数据表格 -->
    <el-card class="test-card">
      <div class="card-header">
        <h3>测试数据</h3>
        <el-button type="success" @click="loadTestData">加载数据</el-button>
      </div>
      
      <el-table :data="testData" border stripe>
        <el-table-column prop="outboundId" label="出库ID" width="80" />
        <el-table-column prop="outboundOrderNumber" label="出库单号" width="180" />
        <el-table-column prop="Approval" label="审核状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getApprovalStatusType(row.Approval)">
              {{ getApprovalStatusText(row.Approval) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" width="150" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="testSingleRecord(row)">
              测试此记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  getAllOutboundOrders, 
  updateApprovalStatus,
  type OutboundOrder 
} from '@/api/outboundOrder'

// 诊断状态
const diagnosing = ref(false)
const currentStep = ref(0)
const diagnosisResults = ref<Array<{
  time: string
  type: 'info' | 'success' | 'warning' | 'error'
  message: string
  data?: any
}>>([])

// 测试数据
const testData = ref<OutboundOrder[]>([])

// 添加诊断结果
const addResult = (type: 'info' | 'success' | 'warning' | 'error', message: string, data?: any) => {
  const time = new Date().toLocaleTimeString()
  diagnosisResults.value.unshift({ time, type, message, data })
  console.log(`[${type.toUpperCase()}] ${message}`, data)
}

// 清空结果
const clearResults = () => {
  diagnosisResults.value = []
}

// 获取审核状态文本
const getApprovalStatusText = (status: string) => {
  if (!status || status.trim() === '' || status === null || status === undefined) {
    return '待审核'
  }
  
  const trimmedStatus = status.trim()
  
  switch (trimmedStatus) {
    case '待审核':
    case '0':
      return '待审核'
    case '审核通过':
    case '通过':
    case '1':
      return '审核通过'
    case '驳回':
    case '拒绝':
    case '2':
      return '驳回'
    default:
      return '待审核'
  }
}

// 获取审核状态标签类型
const getApprovalStatusType = (status: string) => {
  if (!status || status.trim() === '' || status === null || status === undefined) {
    return 'warning'
  }
  
  const trimmedStatus = status.trim()
  
  switch (trimmedStatus) {
    case '待审核':
    case '0':
      return 'warning'
    case '审核通过':
    case '通过':
    case '1':
      return 'success'
    case '驳回':
    case '拒绝':
    case '2':
      return 'danger'
    default:
      return 'warning'
  }
}

// 加载测试数据
const loadTestData = async () => {
  try {
    addResult('info', '开始加载测试数据...')
    
    const response = await getAllOutboundOrders(true) // 强制刷新
    
    if (response.code === 200) {
      testData.value = response.data.map((item: OutboundOrder) => {
        if (!item.Approval || item.Approval === null || item.Approval === undefined) {
          item.Approval = '待审核'
          addResult('warning', `记录 ${item.outboundId} 审核状态为空，设置为待审核`)
        }
        return item
      })
      
      addResult('success', `成功加载 ${testData.value.length} 条记录`, {
        records: testData.value.map(item => ({
          outboundId: item.outboundId,
          outboundOrderNumber: item.outboundOrderNumber,
          Approval: item.Approval
        }))
      })
      
      ElMessage.success('测试数据加载成功')
    } else {
      addResult('error', `加载失败: ${response.msg}`)
      ElMessage.error(response.msg || '加载失败')
    }
  } catch (error) {
    addResult('error', `加载异常: ${error}`)
    console.error('加载测试数据失败:', error)
    ElMessage.error('加载失败')
  }
}

// 测试单个记录
const testSingleRecord = async (row: OutboundOrder) => {
  addResult('info', `开始测试记录: ${row.outboundOrderNumber}`, {
    outboundId: row.outboundId,
    currentStatus: row.Approval
  })
  
  try {
    // 选择测试状态
    const testStatus = row.Approval === '待审核' ? '审核通过' : '待审核'
    
    addResult('info', `执行审核操作: ${row.Approval} -> ${testStatus}`)
    
    const response = await updateApprovalStatus({
      outboundId: row.outboundId,
      Approval: testStatus,
      modifiedBy: 'diagnosis-test',
      remarks: '诊断测试'
    })
    
    addResult('info', '审核API响应', response)
    
    if (response.code === 200) {
      addResult('success', '审核API调用成功')
      
      // 等待后重新加载数据验证
      setTimeout(async () => {
        addResult('info', '重新加载数据验证更新结果...')
        
        const verifyResponse = await getAllOutboundOrders(true)
        
        if (verifyResponse.code === 200) {
          const updatedRecord = verifyResponse.data.find((item: OutboundOrder) => 
            item.outboundId === row.outboundId
          )
          
          if (updatedRecord) {
            addResult('info', '验证结果', {
              expected: testStatus,
              actual: updatedRecord.Approval,
              match: updatedRecord.Approval === testStatus
            })
            
            if (updatedRecord.Approval === testStatus) {
              addResult('success', '✅ 状态更新验证成功')
              ElMessage.success('测试成功：状态已正确更新')
            } else {
              addResult('error', '❌ 状态更新验证失败')
              ElMessage.error('测试失败：状态未正确更新')
            }
          } else {
            addResult('error', '未找到更新后的记录')
          }
        } else {
          addResult('error', `验证数据加载失败: ${verifyResponse.msg}`)
        }
      }, 2000)
    } else {
      addResult('error', `审核API调用失败: ${response.msg}`)
      ElMessage.error('测试失败：审核API调用失败')
    }
  } catch (error) {
    addResult('error', `测试异常: ${error}`)
    console.error('测试异常:', error)
    ElMessage.error('测试异常')
  }
}

// 运行完整诊断
const runDiagnosis = async () => {
  diagnosing.value = true
  currentStep.value = 0
  
  try {
    // 步骤1: 检查数据
    addResult('info', '=== 步骤1: 检查当前数据状态 ===')
    currentStep.value = 1
    
    await loadTestData()
    
    if (testData.value.length === 0) {
      addResult('error', '没有找到测试数据，诊断终止')
      return
    }
    
    // 分析数据状态
    const statusCounts = testData.value.reduce((acc, item) => {
      const status = getApprovalStatusText(item.Approval)
      acc[status] = (acc[status] || 0) + 1
      return acc
    }, {} as Record<string, number>)
    
    addResult('info', '数据状态统计', statusCounts)
    
    // 步骤2: 测试审核
    addResult('info', '=== 步骤2: 执行审核操作测试 ===')
    currentStep.value = 2
    
    // 选择第一条记录进行测试
    const testRecord = testData.value[0]
    await testSingleRecord(testRecord)
    
    // 步骤3: 验证更新
    addResult('info', '=== 步骤3: 验证状态更新 ===')
    currentStep.value = 3
    
    // 等待验证完成
    setTimeout(() => {
      addResult('info', '=== 步骤4: 生成诊断报告 ===')
      currentStep.value = 4
      
      // 生成诊断报告
      const report = {
        timestamp: new Date().toISOString(),
        totalRecords: testData.value.length,
        statusDistribution: statusCounts,
        testResults: diagnosisResults.value.filter(r => r.type === 'success' || r.type === 'error')
      }
      
      addResult('info', '诊断报告生成完成', report)
      
      // 总结
      const successCount = diagnosisResults.value.filter(r => r.type === 'success').length
      const errorCount = diagnosisResults.value.filter(r => r.type === 'error').length
      
      if (errorCount === 0) {
        addResult('success', '🎉 诊断完成：所有测试通过')
        ElMessage.success('诊断完成：系统工作正常')
      } else {
        addResult('warning', `⚠️ 诊断完成：发现 ${errorCount} 个问题`)
        ElMessage.warning(`诊断完成：发现 ${errorCount} 个问题，请查看详细结果`)
      }
      
      diagnosing.value = false
    }, 5000)
    
  } catch (error) {
    addResult('error', `诊断过程异常: ${error}`)
    diagnosing.value = false
    ElMessage.error('诊断过程异常')
  }
}
</script>

<style scoped>
.approval-diagnosis-container {
  padding: 20px;
}

.diagnosis-card, .result-card, .test-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.diagnosis-results {
  max-height: 500px;
  overflow-y: auto;
}

.result-item {
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 4px;
  border-left: 4px solid;
}

.result-item.info {
  background-color: #f0f9ff;
  border-left-color: #409eff;
}

.result-item.success {
  background-color: #f0f9ff;
  border-left-color: #67c23a;
}

.result-item.warning {
  background-color: #fdf6ec;
  border-left-color: #e6a23c;
}

.result-item.error {
  background-color: #fef0f0;
  border-left-color: #f56c6c;
}

.result-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-weight: bold;
}

.result-time {
  color: #909399;
  font-size: 12px;
}

.result-type {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 3px;
}

.result-type.info {
  background-color: #409eff;
  color: white;
}

.result-type.success {
  background-color: #67c23a;
  color: white;
}

.result-type.warning {
  background-color: #e6a23c;
  color: white;
}

.result-type.error {
  background-color: #f56c6c;
  color: white;
}

.result-message {
  margin-bottom: 5px;
  word-break: break-all;
}

.result-data {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
  overflow-x: auto;
}

.result-data pre {
  margin: 0;
  white-space: pre-wrap;
}
</style>


